/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/


const PENDING = "pending" // 等待
const FULFILLED = "fulfilled" // 成功
const REJECTED = "rejected" // 失败

class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch(e) {
      this.reject(e);
    }
  }

   // promsie 状态 
   status = PENDING;
   // 成功之后的值
   value = undefined;
   // 失败后的原因
   reason = undefined;
   // 成功回调
   successCallback = [];
   // 失败回调
   failCallback = [];

   resolve = value => {
    //  如果状态不为等待，就终止代码向下执行
     if (this.status !== PENDING) return
    //  把状态变为成功
    this.status = FULFILLED
    //  将成功的原因保存
    this.value = value
    // 判断成功回调是否存在 以及支持链式调用
    while (this.successCallback.length) this.successCallback.shift()()
   }
   reject = reason => {
     //  如果状态不为等待，就终止代码向下执行
     if (this.status !== PENDING) return
      //  把状态变为成功
      this.status = REJECTED
      //  将成功的原因保存
      this.reason = reason
      // 判断成功回调是否存在 以及支持链式调用
      while (this.failCallback.length) this.failCallback.shift()()
   }
   
   then (successCallback, failCallback) {
      // 参数可选
      successCallback = successCallback ? successCallback : value => value;
      // 参数可选
      failCallback = failCallback ? failCallback: reason => { throw reason };
      let promise2 = new MyPromise((resolve,reject) => {
        // 判断状态是否为成功
        if (this.status === FULFILLED) {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              // 判断 x 的值是普通值还是promise对象
              // 如果是普通值 直接调用resolve 
              // 如果是promise对象 查看promsie对象返回的结果 
              // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        }else if (this.status === REJECTED) {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        } else {
          // 等待
        // 将成功回调和失败回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
        }
      })
   }
   finally (callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value);
    }, reason => {
      return MyPromise.resolve(callback()).then(() => { throw reason })
    })
  }
  catch (failCallback) {
    return this.then(undefined, failCallback)
  }
  static all (array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof MyPromise) {
          // promise 对象
          current.then(value => addData(i, value), reason => reject(reason))
        }else {
          // 普通值
          addData(i, array[i]);
        }
      }
    })
  }
  static resolve (value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise(resolve => resolve(value));
  }
}


function resolvePromise (promise2, x ,resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError("Chaining cycle detected for promise #<Promise>"))
  }
  if (x instanceof MyPromise) {
    // promise对象
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = MyPromise